package cn.touna.jss.modules.third.telecredit;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.TelecreditProperties;
import cn.touna.jss.common.util.DateUtils;
import cn.touna.jss.common.util.MD5Util;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.credit.entity.CarNumberDictEntity;
import cn.touna.jss.modules.credit.service.CarNumberDictService;
import cn.touna.jss.modules.custom.carloan.entity.TrafficViolationEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.exception.BusinessException;
import cn.touna.risk.api.http.HttpUtil;
import cn.touna.risk.api.http.ResultData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 泰尔英福渠道
 *
 * @Author:wuwc
 * @Description:
 * @Date:2018/5/7 17:38
 */
@Service
public class TelecreditService {

    private static final Logger logger = LogManager.getLogger(TelecreditService.class);

    @Autowired
    private TelecreditProperties telecreditProperties;

    @Autowired
    private CarNumberDictService carNumberDictService;

    @ApiMapping(value = "telecredit.trafficViolation",desc = "泰尔英福.车辆交通违章查询")
    public Response trafficViolation(TrafficViolationEntity violationEntity) throws BusinessException {
        ValidUtil.checkRequestParams(violationEntity);
        try {
            String carNumberPrefix = violationEntity.getCarNumber().substring(0, 2);
            List<CarNumberDictEntity> carNumberDictEntityList = carNumberDictService.queryCarNumberDict(carNumberPrefix);
            CarNumberDictEntity carNumberDictEntity = new CarNumberDictEntity();
            if (!CollectionUtils.isEmpty(carNumberDictEntityList)) {
                carNumberDictEntity = carNumberDictEntityList.get(0);
            } else {
                carNumberDictEntity = syncTrafficRegion(carNumberPrefix);
            }
            //按参数规则处理查询违章接口入参
            TrafficViolationEntity dealViolationEntity = new TrafficViolationEntity();
            dealViolationEntity.setCarNumber(violationEntity.getCarNumber());
            int cardCodeLen = violationEntity.getCarCode().length() - carNumberDictEntity.getCarCodeLen();
            String carCode = violationEntity.getCarCode().substring(cardCodeLen);
            int carDriverNumberLen = violationEntity.getCarDriverNumber().length() - carNumberDictEntity.getCarEnginLen();
            String carDriverNumber = violationEntity.getCarDriverNumber().substring(carDriverNumberLen);
            dealViolationEntity.setCarCode(carCode);
            dealViolationEntity.setCarDriverNumber(carDriverNumber);
            return queryTracfficViolation(dealViolationEntity);
        } catch (Exception e) {
            logger.error("REE 【泰尔英福查询】异常,params:{}，msg:{}", violationEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "telecredit.trafficRegion",desc = "泰尔英福.对外车辆违规信息查询")
    public CarNumberDictEntity syncTrafficRegion(String carNumberPrefix) throws Exception {
        Map<String, String> headMap = new HashMap<>();
        try {
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            Map<String, String> bodyMap = new HashMap<>();
            String currentTime = DateUtils.dateTimeToStr(new Date());
            bodyMap.put("currentTime", currentTime);
            bodyMap.put("appKey", telecreditProperties.getAppKey());
            bodyMap.put("token", MD5Util.getSign(currentTime, telecreditProperties.getAppKey(), telecreditProperties.getAppSign()));
            ResultData resultData = HttpUtil.getInstance().postData(telecreditProperties.getRegionalUrl(), headMap, bodyMap);
            logger.info("同步泰尔英福参数规则结果，result:{}", resultData);
            List<CarNumberDictEntity> carNumberDictEntityList = new ArrayList<>();
            if (resultData != null && resultData.getStatus() == 200) {
                CarNumberDictEntity resCarNumberDict = new CarNumberDictEntity();
                JSONArray jsonArray = JSONArray.parseArray(resultData.getData());
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONArray cityJsonArray = JSONUtil.getJSONArray(jsonArray.getJSONObject(i), "Cities", null);
                    for (int k = 0; k < cityJsonArray.size(); k++) {
                        JSONObject cityJson = cityJsonArray.getJSONObject(k);
                        CarNumberDictEntity carNumberDictEntity = new CarNumberDictEntity();
                        carNumberDictEntity.setCityId(cityJson.getString("CityID"));
                        carNumberDictEntity.setCityName(cityJson.getString("CityName"));
                        carNumberDictEntity.setCarNumberPrefix(cityJson.getString("CarNumberPrefix"));
                        carNumberDictEntity.setName(cityJson.getString("Name"));
                        carNumberDictEntity.setCarCodeLen(cityJson.getInteger("CarCodeLen"));
                        carNumberDictEntity.setCarEnginLen(cityJson.getInteger("CarEngineLen"));
                        carNumberDictEntity.setCarOwnerLen(cityJson.getInteger("CarOwnerLen"));
                        carNumberDictEntityList.add(carNumberDictEntity);
                        if (StringUtils.equals(carNumberPrefix, carNumberDictEntity.getCarNumberPrefix())) {
                            resCarNumberDict = carNumberDictEntity;
                        }
                    }
                }
                logger.info("同步泰尔英福参数规则结果，result:{}", carNumberDictEntityList);
                carNumberDictService.saveCarNumberDict(carNumberDictEntityList);
                return resCarNumberDict;
            }
        } catch (Exception e) {
            logger.error("同步泰尔英福参数规则异常，errMsg:{}", e);
            return null;
        }
        return null;
    }

    /**
     * 查询车辆违章详情
     *
     * @param violationEntity
     * @return
     * @throws Exception
     */
    private Response queryTracfficViolation(TrafficViolationEntity violationEntity) throws Exception {
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");
        Map<String, String> bodyMap = new HashMap<>();
        String currentTime = DateUtils.dateTimeToStr(new Date());
        bodyMap.put("currentTime", currentTime);
        bodyMap.put("appKey", telecreditProperties.getAppKey());
        bodyMap.put("token", MD5Util.getSign(currentTime, telecreditProperties.getAppKey(), telecreditProperties.getAppSign(),
                violationEntity.getCarDriverNumber(), violationEntity.getCarNumber(), "02", violationEntity.getCarCode()));
        bodyMap.put("plate", violationEntity.getCarNumber());
        bodyMap.put("plateType", "02");
        bodyMap.put("enginno", violationEntity.getCarDriverNumber());
        bodyMap.put("vehicleIdentificationNumber", violationEntity.getCarCode());
        ResultData resultData = HttpUtil.getInstance().postData(telecreditProperties.getViolationUrl(), headMap, bodyMap);
        if (resultData == null || resultData.getStatus() != 200 || StringUtils.isBlank(resultData.getData())) {
            throw new BusinessException(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
        String result = JSONUtil.getString(resultData.getData(), "data", null);
        String resultCode = JSONUtil.getString(result, "result", null);
        if (!StringUtils.equals(resultCode, "0")) {
            String errMsg = JSONUtil.getString(result, "resultMsg", null);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode(), errMsg);
        }
        return ResponseFactory.success(result);
    }

}
